package com.tjjingpan.networktest

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_main.*
import okhttp3.*
import org.json.JSONArray
import org.xml.sax.InputSource
import org.xmlpull.v1.XmlPullParser
import org.xmlpull.v1.XmlPullParserFactory
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.io.StringReader
import java.net.HttpURLConnection
import java.net.URL
import javax.xml.parsers.SAXParserFactory
import kotlin.concurrent.thread
//借助GSON将JSON数据转换成对象
class App(val id:String,val name:String,val version:String)
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sendRequestBtn.setOnClickListener {
            sendRequestWithOkHttp()
        }
    }

    private fun sendRequestWithHttpURLConnection(){
        thread{
            var connection: HttpURLConnection? = null
            try{
                val response = StringBuilder()
                val url = URL("https://www.baidu.com")
                connection = url.openConnection() as HttpURLConnection
                connection.connectTimeout= 8000
                connection.readTimeout= 8000
                val input = connection.inputStream
                //
                val reader = BufferedReader(InputStreamReader(input))
                reader.use{
                    reader.forEachLine {
                        response.append(it)
                    }
                }
                showResponse(response.toString())

            }catch (e:Exception){
                e.printStackTrace()
            }finally {
                connection?.disconnect()
            }
        }
    }

    private fun sendRequestWithOkHttp(){
//        thread{
//            try{
//                val client = OkHttpClient()
//                val request = Request.Builder()
//                    //.url("https://www.baidu.com")
//                    .url("http://192.168.31.230/get_data.json")
//                    .build()
//                val response = client.newCall(request).execute()
//                val responseData = response.body?.string()
//                if (responseData !=null){
//                    // showResponse(responseData)
//                    //parseXMLWithPull(responseData)
//                    //parseXMLWithSAX(responseData)
//                    //parseJSONWithJSONObject(responseData)
//                    parseJSONWithGSON(responseData)
//                }
//            }catch ( e:Exception){
//                e.printStackTrace()
//            }
//        }

        val address = "http://192.168.31.230/get_data.json"
//        HttpUtil.sendHttpRequest(address,object:HttpCallbackListener{
//            override fun onFinish(response: String) {
//               parseJSONWithGSON(response)
//            }
//            override fun onError(e: Exception) {
//                e.printStackTrace()
//            }
//        })
        HttpUtil.sendOkHttpRequest(address,object:Callback{
            override fun onFailure(call: Call, e: IOException) {
                //在这里对异常情况进行处理
            }

            override fun onResponse(call: Call, response: Response) {
               //得到服务器返回的具体内容
                val responseData = response.body?.string()
                if (responseData != null) {
                    parseJSONWithGSON(responseData)
                }
            }
        })
    }

    private fun showResponse(response :String){
        runOnUiThread{
            responseText.text= response
        }
    }

    //Pull解析
    private fun parseXMLWithPull(xmlData:String){
        try{
            val factory = XmlPullParserFactory.newInstance()
            val xmlPullParser = factory.newPullParser()
            xmlPullParser.setInput(StringReader(xmlData))
            var eventType = xmlPullParser.eventType
            var id = ""
            var name = ""
            var version = ""
            while(eventType != XmlPullParser.END_DOCUMENT) {
                val nodeName = xmlPullParser.name
                when(eventType){
                    //开始解析某个节点
                    XmlPullParser.START_TAG ->{
                        when (nodeName){
                            "id" -> id = xmlPullParser.nextText()
                            "name" -> name = xmlPullParser.nextText()
                            "version" -> version= xmlPullParser.nextText()
                        }
                    }
                    //完成解析某个节点
                    XmlPullParser.END_TAG->{
                        if("app" == nodeName){
                            Log.d("MainActivity","id is $id")
                            Log.d("MainActivity","name is $name")
                            Log.d("MainActivity","version is $version")
                        }
                    }
                }
                eventType = xmlPullParser.next()
            }
        }catch (e:java.lang.Exception){
            e.printStackTrace()
        }
    }

    //SAX解析
    private fun parseXMLWithSAX(xmlData: String){
        try{
            val factory =SAXParserFactory.newInstance()
            val xmlReader = factory.newSAXParser().xmlReader
            val handler = ContentHandler()
            //将ContentHandler的实例设置到XMLReader中
            xmlReader.contentHandler = handler
            //开始执行解析
            xmlReader.parse(InputSource(StringReader(xmlData)))
        }catch(e:Exception){
            e.printStackTrace()
        }
    }

    //JSONObjecn解析
    private fun parseJSONWithJSONObject(jsonData:String){
        try{
            val jsonArray = JSONArray(jsonData)
            for(i in 0 until jsonArray.length()){
                val jsonObject = jsonArray.getJSONObject(i)
                val id = jsonObject.getString("id")
                val name = jsonObject.getString("name")
                val version = jsonObject.getString("version")
                Log.d("MainActivity","id is $id")
                Log.d("MainActivity","name is $name")
                Log.d("MainActivity","version is $version")
            }
        }catch (e:Exception){
            e.printStackTrace()
        }
    }

    //GSON解析
    private fun parseJSONWithGSON(jsonData: String){
        val gson = Gson()
        val typeOf = object :TypeToken<List<App>>(){}.type
        val appList = gson.fromJson<List<App>>(jsonData,typeOf)
        for(app in appList){
            Log.d("MainActivity","id is ${app.id}")
            Log.d("MainActivity","name is ${app.name}")
            Log.d("MainActivity","version is ${app.version}")
        }
    }


}